package com.emellend.api11.preference;

import com.emellend.api11.R;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceActivity;
import android.widget.Toast;

public class AdvancedPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
	
	public static final String KEY_MY_PREFERENCE = "my_preference";
    public static final String KEY_ADVANCED_CHECKBOX_PREFERENCE = "advanced_checkbox_preference";
    
	private CheckBoxPreference checkBoxPreference;
	private Handler handler=new Handler();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.advanced_preferences);
		checkBoxPreference = 
				(CheckBoxPreference) getPreferenceScreen().findPreference(KEY_ADVANCED_CHECKBOX_PREFERENCE);
		
	}
	
	private Runnable forceCheckBoxRunnable=new Runnable() {
		@Override
		public void run() {
			if (checkBoxPreference!=null) {
				checkBoxPreference.setChecked(!checkBoxPreference.isChecked());
			}
			handler.postDelayed(this, 1000);
		}
	};
	
	@Override
	protected void onResume() {
		super.onResume();
		forceCheckBoxRunnable.run();
		getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
		handler.removeCallbacks(forceCheckBoxRunnable);
	}
	
	
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		if (key.equals(KEY_MY_PREFERENCE)) {
			Toast.makeText(this, "Thanks! You increased my count to "+
					sharedPreferences.getInt(key, 0), 0).show();
		}
	};
}
